package com.sdwz.borrow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.jdbc.StringUtils;
import com.sdwz.borrow.client.LibraryClient;
import com.sdwz.borrow.client.UserClient;
import com.sdwz.borrow.entity.AppointmentInfo;
import com.sdwz.borrow.entity.BookInfo;
import com.sdwz.borrow.entity.BorrowInfo;
import com.sdwz.borrow.entity.vo.AppointmentVo;
import com.sdwz.borrow.mapper.AppointmentInfoMapper;
import com.sdwz.borrow.service.AppointmentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sdwz.borrow.service.BorrowInfoService;
import com.sdwz.commonutil.exception.LibraryException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * <p>
 * 预约信息表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-03-30
 */
@Service
public class AppointmentInfoServiceImpl extends ServiceImpl<AppointmentInfoMapper, AppointmentInfo> implements AppointmentInfoService {

    @Autowired
    LibraryClient libraryClient;
    @Autowired
    UserClient userClient;

    @Autowired
    BorrowInfoService borrowInfoService;
    /**
     * 添加预约信息
     * @param userId
     * @param bookIds
     * @return
     */
    @Override
    public List<Map<String,Object>> addAppointments(String userId, List<String> bookIds) {
        List<Map<String,Object>> result = new ArrayList<>();
        ArrayList<String> bookIdList = new ArrayList<>();
        for (String bookId:bookIds){
            AppointmentInfo appointmentInfo = new AppointmentInfo();
            BookInfo book = libraryClient.getBook(bookId);
            if (book.getLoanableQuantity()==0){
                Map<String,Object> map= new HashMap<>();
                map.put("code",201);
                map.put("book",book);
                map.put("message","《"+book.getBookName()+"》无可借阅数");
                result.add(map);
                continue;
            }
            //查看是否借过该书
            QueryWrapper<BorrowInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("book_id",bookId).eq("user_id",userId).ne("status",0);
            int count = borrowInfoService.count(wrapper);
            if (count>0){
                Map<String,Object> map= new HashMap<>();
                map.put("code",201);
                map.put("book",book);
                map.put("message","《"+book.getBookName()+"》不能重复借阅");
                result.add(map);
                continue;
            }
            QueryWrapper<AppointmentInfo> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("book_id",bookId).eq("user_id",userId).eq("status",0);
            int count2 = baseMapper.selectCount(wrapper2);
            if (count2>0){
                Map<String,Object> map= new HashMap<>();
                map.put("code",201);
                map.put("book",book);
                map.put("message","《"+book.getBookName()+"》已借阅，请勿重复借阅");
                result.add(map);
                continue;
            }


            //改变书籍信息的可借阅数
            BookInfo bookInfo = new BookInfo();
            bookInfo.setId(bookId);
            bookInfo.setLoanableQuantity(book.getLoanableQuantity()-1);
            libraryClient.changeLoanableQuantity(bookInfo);

            //添加预约信息
            appointmentInfo.setBookId(bookId);
            appointmentInfo.setUserId(userId);
            appointmentInfo.setAppointmentTime(new Date());
            LocalDateTime localDateTime = LocalDateTime.now().plusDays(3);
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime zdt = localDateTime.atZone(zoneId);//Combines this date-time with a time-zone to create a  ZonedDateTime.
            Date date = Date.from(zdt.toInstant());
            appointmentInfo.setEndTime(date);
            appointmentInfo.setStatus(0);
            baseMapper.insert(appointmentInfo);

            //删除书架书籍

            bookIdList.add(bookId);
            userClient.delShelfBooksByBookIds(userId,bookIdList);
            bookIdList.set(0,null);

            HashMap<String, Object> map = new HashMap<>();
            map.put("code",200);
            map.put("book",book);
            map.put("message","《"+book.getBookName()+"》预约成功");
            result.add(map);

        }

        return result;
    }

    /**
     * 查看个人预约信息
     * @param userId
     * @return
     */
    @Override
    public List<AppointmentVo> getAppointmentInfoByUserId(String userId) {
        List<AppointmentVo> result=new ArrayList<>();
        QueryWrapper<AppointmentInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id",userId).eq("status",0);
        List<AppointmentInfo> appointmentInfos1 = baseMapper.selectList(wrapper1);
//        QueryWrapper<AppointmentInfo> wrapper2 = new QueryWrapper<>();
//        wrapper2.eq("user_id",userId).eq("status",-1);
//        List<AppointmentInfo> appointmentInfos2 = baseMapper.selectList(wrapper2);

//        appointmentInfos1.addAll(appointmentInfos2);

        for (AppointmentInfo appointmentInfo:appointmentInfos1){
            AppointmentVo appointmentVo = new AppointmentVo();
            BeanUtils.copyProperties(appointmentInfo,appointmentVo);
            appointmentVo.setStartTime(appointmentInfo.getCreateTime());

            BookInfo book = libraryClient.getBook(appointmentInfo.getBookId());
            appointmentVo.setBookName(book.getBookName());
            appointmentVo.setAuthor(book.getAuthor());

            //如果超出预约截至时间未取书，返回数据状态为-1但不改变数据库数据
            if (appointmentVo.getEndTime().before(new Date())){
                appointmentVo.setStatus(-1);
            }
            result.add(appointmentVo);
        }


        return result;
    }

    /**
     * 分页多条件查询预约信息
     * @param current
     * @param limit
     * @param appointmentVo
     */
    @Override
    public Map<String,Object> appointmentPages(Long current, Long limit, AppointmentVo appointmentVo) {
        Page<AppointmentInfo> page = new Page<>(current,limit);

        QueryWrapper<AppointmentInfo> wrapper = new QueryWrapper<>();
        wrapper.ne("status",1);
        String userId = appointmentVo.getUserId();
        Integer status = appointmentVo.getStatus();
        if (appointmentVo != null ){
            wrapper.eq("status",0);
        }
        if (!StringUtils.isNullOrEmpty(userId)){
            wrapper.eq("user_id",userId);
        }
        if (status != null && status != -1){
            wrapper.eq("status",status);
        } else if (status != null && status == -1){
            wrapper.eq("status",0);
            wrapper.lt("end_time",new Date());
        }

        Page<AppointmentInfo> selectPage = baseMapper.selectPage(page, wrapper);

        List<AppointmentInfo> records = selectPage.getRecords();
        long total = selectPage.getTotal();
        long size = selectPage.getSize();
        long pageCurrent = selectPage.getCurrent();

        Map<String,Object> result = new HashMap<>();
        result.put("total",total);
        result.put("size",size);
        result.put("current",pageCurrent);
        List<AppointmentVo> appointmentVos = new ArrayList<>();

        for (AppointmentInfo appointmentInfo:records){
            AppointmentVo appointmentVo1 = new AppointmentVo();
            BeanUtils.copyProperties(appointmentInfo,appointmentVo1);
            appointmentVo1.setStartTime(appointmentInfo.getCreateTime());

            String bookId = appointmentInfo.getBookId();

            BookInfo book = libraryClient.getBook(bookId);
            appointmentVo1.setBookName(book.getBookName());
            appointmentVo1.setAuthor(book.getAuthor());

            if (appointmentVo1.getEndTime().before(new Date())){
                appointmentVo1.setStatus(-1);
            }

            appointmentVos.add(appointmentVo1);
        }

        result.put("records",appointmentVos);

        return result;


    }


}
